#! user/bin/python
# -*- coding: utf-8 -*-

"""
Created on 2021/8/26 10:53

@File: 基本接口的实际应用.py
@Author: LT
@Description:
"""
from email.message import Message
from email.parser import Parser

# ------------------------------------------------
# 创建一个Message对象，将题头赋值给它的键，然后把它的负载设为消息主体；然后将它转换成字符串文本生成邮件（消息）文本
# ------------------------------------------------
m = Message()
m['from'] = '284618025@qq.com'
m['to'] = '284618025@qq.com'
m.set_payload('The owls are not what they seem...')
s = str(m)
print(s)

# ------------------------------------------------
# 解析消息文本（比如用于从poplib获得的邮件中解析）；就是上一步的逆操作
# ------------------------------------------------
print('-' * 50)
x = Parser().parsestr(s)
print(type(x))
print(x.get('from'))
print(x.get_payload())
print(x.items())

# ------------------------------------------------
# walk生成器把消息的各个分组进行遍历；如果是单组分，那它就是一封村文本的邮件
# ------------------------------------------------
print('-' * 50)
for part in x.walk():
    print(x.get_content_type())
    print(x.get_payload())
